package com.easyUtils.utils.httpClientUtil.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.core5.util.Timeout;

@Slf4j
@Data
public class HttpClientUtilConfig {

    /** 静态HttpClient实例（线程安全，全局复用） */
    private CloseableHttpClient httpClient;
    private Integer connectSecondTimeout=5;
    private Integer responseSecondTimeout=10;
    private Integer connectionRequestSecondTimeout=2;


    /**
     * 获取指定配置的HttpClient实例
     * @param connectSecondTimeout
     * @param responseSecondTimeout
     * @param connectionRequestSecondTimeout
     * @return
     */
    public HttpClientUtilConfig(Integer connectSecondTimeout, Integer responseSecondTimeout, Integer connectionRequestSecondTimeout) {
        httpClient = HttpClients.custom()
                .setDefaultRequestConfig(RequestConfig.custom()
                        .setConnectTimeout(Timeout.ofSeconds(Long.valueOf(connectSecondTimeout)))   // 连接超时（建立TCP连接的最大时间）
                        .setResponseTimeout(Timeout.ofSeconds(Long.valueOf(responseSecondTimeout))) // 响应超时（等待服务器响应的最大时间）
                        .setConnectionRequestTimeout(Timeout.ofSeconds(Long.valueOf(connectionRequestSecondTimeout))) // 从连接池获取连接的超时
                        .build())
                //配置连接池（全局最大连接数、每个路由的最大连接数）
                .setConnectionManager(new PoolingHttpClientConnectionManager())
                .build();

    }
    /**
     * 获取默认配置的HttpClient实例
     * @return
     */
    public HttpClientUtilConfig() {
        httpClient = HttpClients.custom()
                .setDefaultRequestConfig(RequestConfig.custom()
                        .setConnectTimeout(Timeout.ofSeconds(Long.valueOf(connectSecondTimeout)))   // 连接超时（建立TCP连接的最大时间）
                        .setResponseTimeout(Timeout.ofSeconds(Long.valueOf(responseSecondTimeout))) // 响应超时（等待服务器响应的最大时间）
                        .setConnectionRequestTimeout(Timeout.ofSeconds(Long.valueOf(connectionRequestSecondTimeout))) // 从连接池获取连接的超时
                        .build())
                //配置连接池（全局最大连接数、每个路由的最大连接数）
                .setConnectionManager(new PoolingHttpClientConnectionManager())
                .build();

    }

    /**
     * 获取默认配置的HttpClient实例
     * @return
     */
    public CloseableHttpClient getHttpClientBuild(){
        return new HttpClientUtilConfig(connectSecondTimeout, responseSecondTimeout, connectionRequestSecondTimeout).getHttpClient();
    }

}
